package rhc.singleNodeSpider.execute;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import rhc.singleNodeSpider.BasicComponent;
import rhc.singleNodeSpider.spiderManage.SpiderManage;
import rhc.taskSchedule.taskSignalCall.CustomCall;

/**任务调度器的回调管理
 * @author rhc
 *
 */
public class CustomCallTaskScheduleManage extends BasicComponent {

	private SpiderManage spiderManage;
	
	/**
	 * 任务id对应的主动调用任务调度器回调
	 */
	private Map<String,CustomCall> taskId_customCall=new HashMap<String,CustomCall>();
	
	public CustomCallTaskScheduleManage(SpiderManage spiderManage){
		this.spiderManage=spiderManage;
	}
	
	/**获取正在运行任务id
	 * @return
	 * @throws Exception
	 */
	public List<String> getRunningTaskId() throws Exception{
		return new LinkedList<String>(taskId_customCall.keySet());
	}
	
	/**创建一个任务
	 * @param taskId
	 * @throws Exception
	 */
	public void registerTaskCustomCall(String taskId,CustomCall customCall) throws Exception{
		taskId_customCall.put(taskId, customCall);
	}
	
	/**运行一个任务
	 * @param taskId
	 * @throws Exception
	 */
	public void runTask(String taskId) throws Exception{
		spiderManage.regainTask(taskId);
		CustomCall customCall=this.getCustomCallByTaskId(taskId);
		customCall.run();
	}
	
	/**停止一个任务
	 * @param taskId
	 * @throws Exception
	 */
	public void stopTask(String taskId) throws Exception{
		spiderManage.stopTask(taskId);
		spiderManage.regainTask(taskId);
		
		CustomCall customCall=this.getCustomCallByTaskId(taskId);
		customCall.stop();
		
		taskId_customCall.remove(taskId);
	}
	
	/**暂停一个任务
	 * @param taskId
	 * @throws Exception
	 */
	public void pauseTask(String taskId) throws Exception{
		spiderManage.pauseTask(taskId);
		CustomCall customCall=this.getCustomCallByTaskId(taskId);
		customCall.pause();
	}
	
	/**恢复一个任务
	 * @param taskId
	 * @throws Exception
	 */
	public void regainTask(String taskId) throws Exception{
		spiderManage.regainTask(taskId);
		CustomCall customCall=this.getCustomCallByTaskId(taskId);
		customCall.regain();
	}
	
	/**是否包含某一个任务
	 * @param taskId
	 * @return
	 * @throws Exception
	 */
	public boolean containsTask(String taskId) throws Exception{
		return taskId_customCall.containsKey(taskId);
	}
	
	/**根据任务id获取平台的回调
	 * @param taskId
	 * @return
	 * @throws Exception
	 */
	private CustomCall getCustomCallByTaskId(String taskId) throws Exception{
		CustomCall customCall=taskId_customCall.get(taskId);
		if(null == customCall){
			throw new IllegalArgumentException(taskId+" 不存在");
		}
		return customCall;
	}
}
